/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.delegate.TaskListener;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.history.HistoryLevel;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.IdentityLinkType;
import com.je.bpm.engine.task.Task;
import com.je.bpm.engine.task.TaskInfo;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Date;

/**
 *
 */
public class SaveTaskCmd implements Command<Task>, Serializable {

    private static final long serialVersionUID = 1L;

    protected TaskEntity task;

    public SaveTaskCmd(Task task) {
        this.task = (TaskEntity) task;
    }

    public Task execute(CommandContext commandContext) {
        if (task == null) {
            throw new ActivitiIllegalArgumentException("task is null");
        }

        if (task.getRevision() == 0) {
            commandContext.getTaskEntityManager().insert(task, null);
            if (commandContext.getEventDispatcher().isEnabled()) {
                commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
                if (task.getAssignee() != null) {
                    commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
                }
            }
        } else {
            TaskInfo originalTaskEntity = null;
            if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
                originalTaskEntity = commandContext.getHistoricTaskInstanceEntityManager().findById(task.getId());
            }

            if (originalTaskEntity == null) {
                originalTaskEntity = commandContext.getTaskEntityManager().findById(task.getId());
            }

            String originalName = originalTaskEntity.getName();
            String originalAssignee = originalTaskEntity.getAssignee();
            String originalOwner = originalTaskEntity.getOwner();
            String originalDescription = originalTaskEntity.getDescription();
            Date originalDueDate = originalTaskEntity.getDueDate();
            int originalPriority = originalTaskEntity.getPriority();
            String originalCategory = originalTaskEntity.getCategory();
            String originalFormKey = originalTaskEntity.getFormKey();
            String originalParentTaskId = originalTaskEntity.getParentTaskId();
            String originalTaskDefinitionKey = originalTaskEntity.getTaskDefinitionKey();

            // Only update history if history is enabled
            if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {

                if (!StringUtils.equals(originalName, task.getName())) {
                    commandContext.getHistoryManager().recordTaskNameChange(task.getId(), task.getName());
                }
                if (!StringUtils.equals(originalDescription, task.getDescription())) {
                    commandContext.getHistoryManager().recordTaskDescriptionChange(task.getId(), task.getDescription());
                }
                if ((originalDueDate == null && task.getDueDate() != null)
                        || (originalDueDate != null && task.getDueDate() == null)
                        || (originalDueDate != null && !originalDueDate.equals(task.getDueDate()))) {
                    commandContext.getHistoryManager().recordTaskDueDateChange(task.getId(), task.getDueDate());
                }
                if (originalPriority != task.getPriority()) {
                    commandContext.getHistoryManager().recordTaskPriorityChange(task.getId(), task.getPriority());
                }
                if (!StringUtils.equals(originalCategory, task.getCategory())) {
                    commandContext.getHistoryManager().recordTaskCategoryChange(task.getId(), task.getCategory());
                }
                if (!StringUtils.equals(originalFormKey, task.getFormKey())) {
                    commandContext.getHistoryManager().recordTaskFormKeyChange(task.getId(), task.getFormKey());
                }
                if (!StringUtils.equals(originalParentTaskId, task.getParentTaskId())) {
                    commandContext.getHistoryManager().recordTaskParentTaskIdChange(task.getId(), task.getParentTaskId());
                }
                if (!StringUtils.equals(originalTaskDefinitionKey, task.getTaskDefinitionKey())) {
                    commandContext.getHistoryManager().recordTaskDefinitionKeyChange(task.getId(), task.getTaskDefinitionKey());
                }

            }

            if (!StringUtils.equals(originalOwner, task.getOwner())) {
                if (task.getProcessInstanceId() != null) {
                    commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(), task.getOwner(), IdentityLinkType.PARTICIPANT);
                }
                commandContext.getHistoryManager().recordTaskOwnerChange(task.getId(), task.getOwner());
            }
            if (!StringUtils.equals(originalAssignee, task.getAssignee())) {
                if (task.getProcessInstanceId() != null) {
                    commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(), task.getAssignee(), IdentityLinkType.PARTICIPANT);
                }
                commandContext.getHistoryManager().recordTaskAssigneeChange(task.getId(), task.getAssignee());

                commandContext.getProcessEngineConfiguration().getListenerNotificationHelper().executeTaskListeners(task, TaskListener.EVENTNAME_ASSIGNMENT);
                commandContext.getHistoryManager().recordTaskAssignment(task);

                if (commandContext.getEventDispatcher().isEnabled()) {
                    commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
                }

            }

            return commandContext.getTaskEntityManager().update(task);

        }


        return null;
    }

}
